import { createRouter, createWebHistory } from 'vue-router'
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils'
import http from '@/utils/httpRequest'
import VueCookies from 'vue-cookies'


// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  {path:'/404', component:()=>import('@/views/common/404.vue'), name:'404', meta:{}},
  {path:'/login', component:()=>import('@/views/common/Login.vue'), name:'login', meta:{}}
]


// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path:'/',
  component:import('@/views/main.vue'),
  name:'main',
  meta:{},
  redirect: { name: 'home' },
  children:[
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    {path:'/home', component:()=>import('@/views/common/Home.vue'), name:'home', meta:{}}
  ],
  beforeEnter(to,from,next){
    //未登录直接进入login
    console.log('ll', VueCookies)
    var authorization = VueCookies.get('Authorization')
    if(!authorization || !/\S/.test(authorization)){
      clearLoginInfo()
      next({name:'login'})
    }
    next()
  }
}


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: globalRoutes.concat(mainRoutes),
  scrollBehavior:()=>{y:0},
  isAddDynamicMenuRoutes:false // 是否已经添加动态(菜单)路由
})


router.beforeEach((to,  from,  next)=>{
  console.log('before', to, from)
  console.log('lltt', VueCookies)

  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
    if(router.options.isAddDynamicMenuRoutes || currentRouteType(to, globalRoutes) === 'global'){
      next()
    }else{
      //http 远程请求menus
      http({
        url:http.adornUrl('/sys/menu/nav'),
        method:'get',
        params:http.adornParams()
      }).then(({data})=>{
        sessionStorage.setItem('authorities', JSON.stringify(data.authorities || '[]'))
        addDynamicMenuRoutes(data.menuList)
        router.options.isAddDynamicMenuRoutes = true
        sessionStorage.setItem('menuList', JSON.stringify(data.menuList))
        next({...to, replace:true})
      }).catch((e)=>{
        console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
        router.push({name:'login'})
      })
    }
})


/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function currentRouteType(to, globalRoutes = []){
  var tmp = []
  for(var index = 0; index < globalRoutes.length; index++){
    if(to.path == globalRoutes[index].path){
      return 'global'
    }else if(globalRoutes[index].children && globalRoutes[index].children.length >= 1){
      tmp = tmp.concat(globalRoutes[index].children)
    }
  }

  return tmp.length>=1?getLayoutType(to, tmp):'main'
}


/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicMenuRoutes(menuList = [], routes = []){
  var tmp = []
  for(var index = 0; index < menuList.length; index++){
    var menu = menuList[index]
    //解析数据并加入
    if(menu.children && menu.children.length > 0){
      tmp = tmp.concat(menu.children)
    }else if( menu.url && /\S/.test(menu.url)){
      menu.url = menu.url.replace(/^\//, '')
      var route = {
        path:menu.url.replace('/', '-'),
        component:null,
        name:menu.url.replace('/', '-'),
        meta:{
          menuId:menu.menuId,
          title:menu.name,
          idDynamic:true,
          isTab:true,
          iframeUrl:''
        }
      }      

      if(isURL(menu.url)){
        route['path'] = `i-${menu.menuId}`
        route['name'] = `i-${menu.menuId}`
        route['meta']['iframeUrl'] = menu.url
      }else{
        try{ //动态加载layout
          route['component'] = ()=> import(`@/views/modules/${menu.url}.vue`) || null
        }catch(e){}
      }
      //加入
      routes.push(route)
    }
  }

  if( tmp.length >= 1){
    addDynamicMenuRoutes(tmp, routes)
  }else{
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoute(mainRoutes)
    router.addRoute({path:'/:pathMatch(.*)*', component:import('@/views/common/404.vue'), name:'not found' })
    router.addRoute({path:'/:pathMatch(.*)',  component:import('@/views/common/404.vue'), name:'not found' })
  }
  sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
}


export default router
